const app = getApp()
const db = wx.cloud.database()
Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    Custom: app.globalData.Custom,
    TabCur: 0,
    MainCur: 0,
    VerticalNavTop: 0,
    list: [],
    contactAll: [],
    load: true,
    isonload: false
  },
  onLoad: function(options) {
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    db.collection('classification').get().then(res => {
      let list = [{}];
      list = res.data
      var contactAll = []
      for (let i = 0; i < list.length; i++) {
        contactAll[i] = new Array()
      }
      const MAX_LIMIT = 20
      db.collection('goods').count().then(res => {
        const total = res.total
        const batchTimes = Math.ceil(total / 20)
        const tasks = []
        for (let i = 0; i < batchTimes; i++) {
          const promise = db.collection('goods').skip(i * MAX_LIMIT).limit(MAX_LIMIT).get();
          tasks.push(promise)
        }
        Promise.all(tasks).then((result) => {
          let concatData = []
          for (let i = 0; i < result.length; i++) {
            concatData = concatData.concat(result[i].data)
          }
          for (let i = 0; i < concatData.length; i++) {
            let index = concatData[i].classification
            concatData[i].num = 0
            contactAll[index].push(concatData[i])
          }
          var userInfo = wx.getStorageSync('userInfo');
          if (userInfo != "") {
            db.collection('shoppingcart').where({
              _openid: userInfo.openid
            }).get().then(res => {
              var shoppingdetail = res.data
              for (let i = 0; i < shoppingdetail.length; i++) {
                var idx1 = shoppingdetail[i].classification
                var item = contactAll[idx1]
                for (let j = 0; j < item.length; j++) {
                  if (item[j].code == shoppingdetail[i].code) {
                    contactAll[idx1][j].num = shoppingdetail[i].num
                  }
                }
              }
              this.setData({
                list: list,
                listCur: list[0],
                contactAll: contactAll,
                isonload: true
              })
              wx.hideLoading()
            })
          } else {
            this.setData({
              list: list,
              listCur: list[0],
              contactAll: contactAll,
              isonload: true
            })
            wx.hideLoading()
          }
        })
      })
    })
  },

  onShow: function() {
    var isonload = this.data.isonload
    if (isonload) {
      var userInfo = wx.getStorageSync('userInfo');
      var contactAll = this.data.contactAll
      if (userInfo != "") {
        for (let i = 0; i < contactAll.length; i++) {
          for (let j = 0; j < contactAll[i].length; j++) {
            contactAll[i][j].num = 0
          }
        }
        db.collection('shoppingcart').where({
          _openid: userInfo.openid
        }).get().then(res => {
          var shoppingdetail = res.data
          for (let i = 0; i < shoppingdetail.length; i++) {
            var idx1 = shoppingdetail[i].classification
            var item = contactAll[idx1]
            for (let j = 0; j < item.length; j++) {
              if (item[j].code == shoppingdetail[i].code) {
                contactAll[idx1][j].num = shoppingdetail[i].num
              }
            }
          }
          this.setData({
            contactAll: contactAll,
          })
        })
      }
    }
  },

  gogooddetail: function(event) {
    var goodinfo = event.currentTarget.dataset.item
    wx.navigateTo({
      url: '../gooddetail/gooddetail?goodinfo=' + JSON.stringify(goodinfo)
    })
  },

  onAddCart: function(event) {
    var userInfo = wx.getStorageSync('userInfo');
    if (userInfo == "") {
      wx.navigateTo({
        url: '../auth/auth'
      })
    } else {
      var id1 = event.currentTarget.dataset.id1
      var id2 = event.currentTarget.dataset.id2
      var contactAll = this.data.contactAll
      contactAll[id1][id2].num = 1
      this.setData({
        contactAll: contactAll
      })
      var goodinfo = contactAll[id1][id2]
      goodinfo.submitdate = db.serverDate()
      goodinfo.openid = userInfo.openid
      delete goodinfo._id
      db.collection('shoppingcart').add({
          data: goodinfo,
        })
        .then(res => {
          var sum = app.globalData.goodnum + 1
          app.globalData.goodnum = sum
          wx.setTabBarBadge({
            index: 2,
            text: sum + ""
          })
        })
        .catch(console.error)
    }
  },

  onPlusNum: function(event) {
    var sum = app.globalData.goodnum + 1
    app.globalData.goodnum = sum
    wx.setTabBarBadge({
      index: 2,
      text: sum + ""
    })
  },

  onMinusNum: function(event) {
    var sum = app.globalData.goodnum - 1
    app.globalData.goodnum = sum
    wx.setTabBarBadge({
      index: 2,
      text: sum + ""
    })
  },

  onChangeNum: function(event) {
    var id1 = event.currentTarget.dataset.id1
    var id2 = event.currentTarget.dataset.id2
    var contactAll = this.data.contactAll
    contactAll[id1][id2].num = event.detail
    var code = contactAll[id1][id2].code
    var userInfo = wx.getStorageSync('userInfo');
    this.setData({
      contactAll: contactAll
    })
    db.collection('shoppingcart').where({
      code: code,
      _openid: userInfo._openid
    }).get().then(res => {
      if (event.detail == 0) {
        db.collection('shoppingcart').doc(res.data[0]._id).remove()
          .then(console.log)
          .catch(console.error)
      } else {
        db.collection('shoppingcart').doc(res.data[0]._id).update({
            data: {
              num: event.detail
            }
          })
          .then(console.log)
          .catch(console.error)
      }
    })
  },

  tabSelect(e) {
    this.setData({
      TabCur: e.currentTarget.dataset.id,
      MainCur: e.currentTarget.dataset.id,
      VerticalNavTop: (e.currentTarget.dataset.id - 1) * 50
    })
  },

  VerticalMain(e) {
    let that = this;
    let list = this.data.list;
    let tabHeight = 0;
    if (this.data.load) {
      for (let i = 0; i < list.length; i++) {
        let view = wx.createSelectorQuery().select("#main-" + list[i].id);
        view.fields({
          size: true
        }, data => {
          list[i].top = tabHeight;
          tabHeight = tabHeight + data.height;
          list[i].bottom = tabHeight;
        }).exec();
      }
      that.setData({
        load: false,
        list: list
      })
    }
    let scrollTop = e.detail.scrollTop + 20;
    for (let i = 0; i < list.length; i++) {
      if (scrollTop > list[i].top && scrollTop < list[i].bottom) {
        that.setData({
          VerticalNavTop: (list[i].id - 1) * 50,
          TabCur: list[i].id
        })
        return false
      }
    }
  }
})